﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;

namespace Maticsoft
{
    /// <summary>
    /// 针对DataTable操作的一些通用方法
    /// </summary>
    public static class DataTableExt
    {
        /// <summary>
        /// 将数据表转换成JSON类型串
        /// </summary>
        /// <param name="dt">要转换的数据表</param>
        /// <returns></returns>
        public static StringBuilder DataTableToJson(DataTable dt)
        {
            return DataTableToJson(dt, true);
        }

        /// <summary>
        /// 将数据表转换成JSON类型串
        /// </summary>
        /// <param name="dt">要转换的数据表</param>
        /// <param name="dtDispose"></param>
        /// <returns></returns>
        public static StringBuilder DataTableToJson(DataTable dt, bool dtDispose)
        {
            return DataTableToJson(dt, dtDispose, false);
        }

        /// <summary>
        /// 将数据表转换成JSON类型串
        /// </summary>
        /// <param name="dt">要转换的数据表</param>
        /// <param name="dtDispose"></param>
        /// <param name="isOutput"></param>
        /// <returns></returns>
        public static StringBuilder DataTableToJson(DataTable dt, bool dtDispose, bool isOutput)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("[");

            //数据表字段名和类型数组
            string[] dtField = new string[dt.Columns.Count];
            string[] dtFieldType = new string[dt.Columns.Count];
            int i = 0;
            string formatStr = "{{";
            string fieldtype;
            foreach (DataColumn dc in dt.Columns)
            {
                dtField[i] = dc.Caption.Trim().ToUpper();
                formatStr += "\"" + dc.Caption.Trim().ToUpper() + "\":";
                fieldtype = dc.DataType.ToString().Trim().ToLower();
                dtFieldType[i] = fieldtype;
                if (fieldtype.IndexOf("int") > 0 || fieldtype.IndexOf("deci") > 0 ||
                    fieldtype.IndexOf("floa") > 0 || fieldtype.IndexOf("doub") > 0 ||
                    fieldtype.IndexOf("bool") > 0)
                {
                    formatStr += "\"{" + i + "}\"";
                }
                else
                {
                    formatStr += "\"{" + i + "}\"";
                }
                formatStr += ",";
                i++;
            }

            if (formatStr.EndsWith(","))
            {
                formatStr = formatStr.Substring(0, formatStr.Length - 1);//去掉尾部","号
            }
            formatStr += "}},";

            i = 0;
            object[] objectArray = new object[dtField.Length];
            foreach (DataRow dr in dt.Rows)
            {
#pragma warning disable 168
                foreach (string fieldname in dtField)
#pragma warning restore 168
                {   //对 \ , ' 符号进行转换 
                    string objStr = string.Empty;
                    objectArray[i] = objStr;
                    if (dr[dtField[i]] != null)
                    {
                        if (dtFieldType[i].IndexOf("datetime") > 0)
                        {
                            if (dr[dtField[i]].ToString() != "")
                            {
                                if (DateTime.Parse(dr[dtField[i]].ToString()).ToString() == DateTime.MaxValue.ToString())
                                {
                                    objStr = "无";
                                }
                                else if (DateTime.Parse(dr[dtField[i]].ToString()).ToString() == DateTime.MinValue.ToString())
                                {
                                    objStr = "不详";
                                }
                                else
                                {
                                    objStr = DateTime.Parse(dr[dtField[i]].ToString()).ToString("yyyy-MM-dd");
                                }
                            }
                            objectArray[i] = objStr;
                        }
                        else
                        {
                            objStr = isOutput ? OutputText(dr[dtField[i]].ToString().Trim().Replace("\\", "\\\\").Replace("'", "\\'").Replace("\r\n", "\\r\\n").Replace("\n", "\\n")) : dr[dtField[i]].ToString().Trim().Replace("\\", "\\\\").Replace("'", "\\'").Replace("\r\n", "\\r\\n").Replace("\n", "\\n");
                            objectArray[i] = ToHex(objStr);
                        }
                    }
                    switch (objectArray[i].ToString())
                    {
                        case "True":
                            {
                                objectArray[i] = "true"; break;
                            }
                        case "False":
                            {
                                objectArray[i] = "false"; break;
                            }
                        default: break;
                    }
                    i++;
                }
                i = 0;
                stringBuilder.Append(string.Format(formatStr, objectArray));
            }
            if (stringBuilder.ToString().EndsWith(","))
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);//去掉尾部","号
            }

            if (dtDispose)
            {
                dt.Dispose();
            }
            return stringBuilder.Append("]");
        }

        /// <summary>
        /// 执行DataTable中的查询返回新的DataTable
        /// </summary>
        /// <param name="dt">源数据DataTable</param>
        /// <param name="condition">查询条件</param>
        /// <returns></returns>
        public static DataTable GetNewDataTable(DataTable dt, string condition)
        {
            DataTable newdt = dt.Clone();
            DataRow[] dr = dt.Select(condition);
            foreach (DataRow t in dr)
            {
                newdt.ImportRow(t);
            }
            return newdt;//返回的查询结果
        }

        /// <summary>
        /// 执行DataTable中的查询返回新的DataTable,并排序
        /// </summary>
        /// <param name="dt">源数据DataTable</param>
        /// <param name="condition">查询条件</param>
        /// <param name="sort">排序条件</param>
        /// <returns></returns>
        public static DataTable GetNewDataTableAndSort(DataTable dt, string condition, string sort)
        {
            DataTable newdt = dt.Clone();
            DataRow[] dr = dt.Select(condition, sort);
            foreach (DataRow t in dr)
            {
                newdt.ImportRow(t);
            }
            return newdt;//返回的查询结果
        }
        private static string ToHex(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] bs = Encoding.Unicode.GetBytes(str);
            for (int i = 0; i < bs.Length; i++)
            {
                byte lobyte = bs[i];
                byte upbyte = bs[++i];

                if (upbyte == 0)
                    sb.Append((char)lobyte);
                else
                {
                    string temp = @"\u";
                    temp += (upbyte).ToString("x2");
                    temp += (lobyte).ToString("x2");
                    sb.Append(temp);
                }
            }
            return sb.ToString();
        }
        private static string OutputText(string outputString)
        {
            if (!string.IsNullOrEmpty(outputString))
            {
                outputString = outputString.Trim();
                outputString = outputString.Replace("&#32;", " ");
                outputString = outputString.Replace("&#33;", "!");
                outputString = outputString.Replace("&#34;", "\"");
                //outputString = outputString.Replace("&#35;", "#");
                outputString = outputString.Replace("&#36;", "$");
                outputString = outputString.Replace("&#37;", "%");
                //outputString = outputString.Replace("&#38;", "&");
                outputString = outputString.Replace("&#39;", "\'");
                outputString = outputString.Replace("&#40;", "(");
                outputString = outputString.Replace("&#41;", ")");
                outputString = outputString.Replace("&#42;", "*");
                outputString = outputString.Replace("&#43;", "+");
                outputString = outputString.Replace("&#44;", ",");
                outputString = outputString.Replace("&#45;", "-");
                outputString = outputString.Replace("&#46;", ".");
                //outputString = outputString.Replace("&#47;", "/");
                outputString = outputString.Replace("&#58;", ":");
                //outputString = outputString.Replace("&#59;", ";");
                outputString = outputString.Replace("&#60;", "<");
                outputString = outputString.Replace("&#61;", "=");
                outputString = outputString.Replace("&#62;", ">");
                outputString = outputString.Replace("&#63;", "?");
                outputString = outputString.Replace("&#64;", "@");
                outputString = outputString.Replace("&#91;", "[");
                //outputString = outputString.Replace("&#92;", "\\/");
                outputString = outputString.Replace("&#93;", "]");
                outputString = outputString.Replace("&#94;", "^");
                outputString = outputString.Replace("&#95;", "_");
                outputString = outputString.Replace("&#96;", "`");
                outputString = outputString.Replace("&#123;", "{");
                outputString = outputString.Replace("&#124;", "|");
                outputString = outputString.Replace("&#125;", "}");
                outputString = outputString.Replace("&#126;", "~");
                outputString = outputString.Replace("&#xFF0C;", "，");
                outputString = outputString.Replace("&#x201C;", "“");
                outputString = outputString.Replace("&#x201D;", "”");
                outputString = outputString.Replace("&ldquo;", "“");
                outputString = outputString.Replace("&rdquo;", "”");
                outputString = outputString.Replace("&mdash;", "—");
                //outputString = outputString.Replace("&#38;", "&");
                //outputString = outputString.Replace("&#35;", "#");
                //outputString = outputString.Replace("&#59;", ";");
                outputString = outputString.Replace("&#x2022;", "•");
                return outputString;
            }
            return "";
        }
    }
}
